package com.movies.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.Key;
import java.security.SecureRandom;

/**
 * Created by admin on 2017/3/26.
 */
public class RC2Utils {

    private static final String ALGORITHM = "RC2";
    private static final BASE64Encoder base64Encoder = new BASE64Encoder();
    private static final BASE64Decoder base64Decoder = new BASE64Decoder();
    private static final String SECRET_KEY = "c7vUXo6Mt8q9jRxZbX5yMg==";

    private static Cipher cipher = null;
    private static Key key = null;

    /**
     * 加密
     * @param plainText
     * @return
     * @throws Exception
     */
    public static String encrypt(String plainText) throws Exception {
        byte[] encryptByte = getCipher().doFinal(plainText.getBytes("UTF-8"));
        return encodeBASE64(encryptByte);
    }

    /**
     * 编码
     * @param inputByte
     * @return
     */
    private static String encodeBASE64(byte[] inputByte) {
        return base64Encoder.encodeBuffer(inputByte);
    }

    /**
     * 解码
     * @param inputText
     * @return
     * @throws IOException
     */
    private static byte[] decodeBASE64(String inputText) throws IOException {
        return base64Decoder.decodeBuffer(inputText);
    }

    /**
     * 根据秘钥生成KEY
     * @return
     * @throws IOException
     */
    private static Key getKey() throws IOException {
        if (null == key) {
            key = new SecretKeySpec(decodeBASE64(SECRET_KEY), ALGORITHM);
        }
        return key;
    }

    /**
     * 获取加密算法
     * @return
     * @throws Exception
     */
    private static Cipher getCipher() throws Exception {
        if (null == cipher) {
            cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, getKey());
        }
        return cipher;
    }

    /**
     * 生成密钥，seed可以为空
     */
    private static String initKey(String seed) throws Exception {
        SecureRandom secureRandom = null;
        if (seed != null) {
            secureRandom = new SecureRandom(decodeBASE64(seed));
        } else {
            secureRandom = new SecureRandom();
        }
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
        kg.init(secureRandom);
        SecretKey secretKey = kg.generateKey();
        return encodeBASE64(secretKey.getEncoded());
    }
}
